package com.zcsy.commons.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class WatermarkUtil {

	/**
	 * @Description 添加文字水印
	 * @param pressText 需要添加的文字
	 * @param srcImageFile 源图片
	 * @param destImageFile 目标图片
	 * @param alpha 透明度  必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
	 * @author yuhaichao yhcjhun@foxmail.com
	 * @date 2015年11月12日
	 */
	public final static void pressText(String pressText, String srcImageFile,
			String destImageFile, float alpha) {
		try {
			File img = new File(srcImageFile);
			Image src = ImageIO.read(img);
			int width = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			// 开文字抗锯齿 去文字毛刺
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
					RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			g.drawImage(src, 0, 0, width, height, null);
			// 设置颜色
			g.setColor(new Color(89, 87, 87));
			// 设置 Font
			g.setFont(new Font("方正兰亭中黑_GBK", Font.BOLD, 54));
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
					alpha));
			int x = width - getWatermarkLength(pressText, g) - 5;  
            int y = height - 15;  
			g.drawString(pressText, x, y);
			g.dispose();
			ImageIO.write((BufferedImage) image, "JPEG",
					new File(destImageFile));// 输出到文件流
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {  
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());  
    }
}